package com.i360day.invoker.context;

import com.i360day.invoker.configuration.HttpInvokerCloudAutoConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.named.NamedContextFactory;
import org.springframework.context.ApplicationContext;

public class InvokerContext extends NamedContextFactory implements HttpInvokerContext {

    private ApplicationContext parent;

    public InvokerContext() {
        super(HttpInvokerCloudAutoConfiguration.class, "invoker", "invoker.client.name");
    }

    @Override
    public void setApplicationContext(ApplicationContext parent) throws BeansException {
        super.setApplicationContext(this.parent = parent);
    }

    @Override
    public ApplicationContext getParent() {
        return parent;
    }

    @Override
    public <T> T getBean(String contextName, String beanName, Class<T> type) {
        return (T) getContext(contextName).getBean(beanName, type);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> type) {
        return (T) getContext(beanName).getBeansOfType(type);
    }

    @Override
    public <T> T getBean(Class<T> type) {
        return (T) getInstance(type.getSimpleName(), type);
    }

    @Override
    public <T> T getBean(Class<T> type, boolean ignoreError) {
        try {
            return getBean(type);
        } catch (Exception ex) {
            //ignore exception
            if (ignoreError) {
                throw ex;
            }
        }
        return null;
    }
}
